package com.bytemonster.last;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
@Scope("prototype")
@Slf4j
public class WsLast extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static ConcurrentHashMap<String, Channel> socket = new ConcurrentHashMap<>();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("客服端新连接加入：{}",ctx.channel().id());
        clients.add(ctx.channel());
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("客服异常断开: {}，原因: {}",ctx.channel().id(),cause.getMessage());
        closeChannel(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客服端连接断开：{}",ctx.channel().id());
        closeChannel(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest request) {
            String uri = request.uri();
            if (StrUtil.isNotBlank(uri)) {
                String key = uri.substring("/websocket/".length());
                log.info("客服端自组编号建立连接：{}" , key);
                if(StrUtil.isNotBlank(key)) {
                    ctx.channel().attr(AttributeKey.valueOf("key")).set(key);
                    socket.put(key, ctx.channel());
                }
                request.setUri("/websocket");
            }
        }
        //建立请求
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        log.info("客服端：{} 发送消息：{}", ctx.channel().id(), textWebSocketFrame.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务端收到您发送的信息：" + textWebSocketFrame.text()));
    }

    private void closeChannel(ChannelHandlerContext ctx) {
        Object key = ctx.attr(AttributeKey.valueOf("key")).get();
        if (!ObjectUtil.isNull(key)) {
            socket.remove(key.toString());
        }
        clients.remove(ctx.channel());
        ctx.close();
    }
}
